﻿using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MVVMOpenChildWindow.Base
{
    public class WindowProvider
    {
        //public static List<Type> types = new List<Type>();
        //public static void Register<T>()
        //{
        //    types.Add(typeof(T));
        //}

        //public static void ShowDialog(string typeName)
        //{
        //    Type type = types.FirstOrDefault(t => t.Name == typeName);
        //    if (type != null)
        //    {
        //        var window = Activator.CreateInstance(type) as Window;
        //        window.Owner = Application.Current.MainWindow;
        //        window.ShowDialog();
        //    }
        //}


        static Dictionary<string, WindowInfo> types = new Dictionary<string, WindowInfo>();

        public static void Register<T>(string key = "",Window owner = null)
        {
            if (string.IsNullOrEmpty(key))
            {
                key = typeof(T).Name;
            }

            if(!types.ContainsKey(key))
                types.Add(key, new WindowInfo() { WinType = typeof(T), Owner = owner });
            
        }

        public static bool ShowDialog(string typeName,object datacontext)
        {
            Type type = null;
            if (types.ContainsKey(typeName))
            {
                type = types[typeName].WinType;
            }
            
            if (type != null)
            {
                var window = Activator.CreateInstance(type) as Window;
                window.Owner = types[typeName].Owner;
                window.DataContext = datacontext;
                return window.ShowDialog() == false;
            }
            else
                throw new ArgumentException("Type not found");
        }
    }

    class WindowInfo
    {
        public Type WinType { get; set; }
        public Window Owner { get; set; }
    }
}
